const {getUserInput}  = require('./src/UserInputUtil')
const {exists,getFileWithSuffix,moveFile,mkdir} = require('./src/FileUtil')
const {Log} = require('./src/LogUtil')
const path = require('path')
const {readExcel,writeExcel} = require('./src/ExcelReadUtil')
const {uploadPhoto} = require('./src/RequestUtil')

//服务器地址
const UploadServerUrl = "https://www.xjve.com/ckStudentUploadApi/uploadGraduatePhoto.do"

//const UploadServerUrl = "http://localhost:8080/ckStudentUploadApi/uploadGraduatePhoto.do"

const main = async ()=>{

	//上传成功 序号
	let uploadSuccessIndex = 1;

	/** 创建日志 */
	const log = new Log(path.join(__dirname,'run.log'))

	await log.log(`时间:${new Date()}`)

	/** 询问上传目录位置 */
	const photoDirectory = await getUserInput('请输入图片目录:\n')
	//const photoDirectory = "C:\\Users\\yeqin\\Desktop\\学生素材导入\\学信网照片"

	/** 询问上传密码 */
	const uploadPassword = await getUserInput('请输入上传密码:\n')

	const [erro1] = await exists(photoDirectory)

	await log.error(erro1)

	/** 创建备份目录 */
	const [mkdirError,backPhotoDirectory] = await mkdir(path.join(photoDirectory,'backup'))

	await log.error(mkdirError)

	/** 寻找excel学信网拍摄的excel文件 */
	const [error2,excelFile] = await getFileWithSuffix(photoDirectory,['.xls','.xlsx'])

	await log.error(error2 ? `请检查目录:${photoDirectory}是否存在新华社的excel文件` : null)

	/** 读取excel信息 */
	const excelData = readExcel(excelFile,log)


	for( let index in excelData){

		/** 根据拍摄序号和学号 获取图片信息和上传 */
		const {sort,num,school,name,idCard} = excelData[index]

		const photoFileName = `IMG_${sort}.JPG`

		const photoFile = path.join(photoDirectory,photoFileName)

		/** 判断图片是否存在于文件夹中 */
		const [erro3] = await exists(photoFile)

		//若不存在
		if(erro3){

			//判断是否存在备份目录中 若还不存在 则报错  存在则跳过
			const [not_exist_inbackup] = await exists(path.join(backPhotoDirectory,photoFileName))
			log.error(not_exist_inbackup ? `图片:${photoFileName}不存在，请检查` : null)

			continue;
		}

		//上传图片  
		const [uploadError,body] = await uploadPhoto(UploadServerUrl,num,photoFile,uploadPassword)

		await log.error(uploadError)

		//上传出现错误
		if(body.error){
			const msg = `[UPLOAD ERROR]:图片上传错误 本地excel:学校:${school} 姓名:${name} 身份证:${idCard},服务器返回:${body.error}`
			await log.log(msg)
			continue;
		}

		await log.log(`${uploadSuccessIndex++}.学号:${num} 图片上传成功。 服务器返回: ${body.value}`)

		/** 移动文件 */
		await moveFile(photoFile,path.join(backPhotoDirectory,photoFileName))//创建目录 移动图片

	}

}

main();
